﻿using System;
using System.Collections.Generic;
using FlowCanvas;
using FlowCanvas.Nodes;
using LogSystem;
using NodeCanvas.Framework;
using ParadoxNotion;
using ParadoxNotion.Design;
using UnityEngine;

namespace Yoozoo.Gameplay.Liberty.Nodes
{
    public class UIPageLifeEvent : EventNode
    {
        public static Action<string> OnPageOpened;
        public static Action<string> OnPageClosed;
        
        [RequiredField]
        public BBParameter<string> pageConfigName;
        //public BBParameter<int> listenCount = 1;

        protected FlowOutput onOpen;
        protected FlowOutput onClose;
        
        public override string name
        {
            get
            {
                return string.Format("{0} ({1})", "UIPageLifeEvent", pageConfigName.value);
            }
        }
        
        protected override void RegisterPorts()
        {
            AddFlowInput("start",OnStart);
            
            onOpen = AddFlowOutput("onOpen");
            onClose = AddFlowOutput("onClose");
        }

        private void OnStart(Flow f)
        {
            Subscribe();
        }

        private void Subscribe()
        {
            OnPageOpened += OnUIPageOpened;
            OnPageClosed += OnUIPageClosed;
        }

        private void UnSubscribe()
        {
            OnPageOpened -= OnUIPageOpened;
            OnPageClosed -= OnUIPageClosed;
        }

        private void OnUIPageOpened(string page)
        {
            if (page == pageConfigName.value)
            {
                UnSubscribe();
                onOpen.Call(new Flow());
            }
        }
        
        private void OnUIPageClosed(string page)
        {
            if (page == pageConfigName.value)
            {
                UnSubscribe();
                onClose.Call(new Flow());
            }
        }

        public override void OnGraphStoped()
        {
            base.OnGraphStoped();
            UnSubscribe();
        }
    }
}